
const Controller = require('egg').Controller;

class bookdetailController extends Controller {

    async BookDetail() {
        const{ctx,app}=this;
        switch (ctx.query.t) {
            case "w1":ctx.query.bid = 1881;break;
            case "w2":ctx.query.bid = 1883;break;
            case "l1":ctx.query.bid = 1882;break;
            case "l2":ctx.query.bid = 1884;break;
            default:ctx.body="押题卷领取页";break;
        }
        //不存在图书id返回
        if (!ctx.query.bid) {
            ctx.redirect('/?nb');
            return;
        }
        let url = app.config.HOST + ctx.originalUrl;

        if (ctx.query.token||ctx.cookies.get("token")){
            let querytoken=ctx.query.token?ctx.query.token:ctx.cookies.get("token")
            try{
                let res_data = await ctx.service.bookdetailService.GetBookDetail(ctx.query.bid,ctx.headers['x-real-ip'], querytoken);
                if(res_data.rescode=="error"){
                    ctx.cookies.set('token'," ");
                    if(res_data.err=="first"){
                        return this.ctx.body="登录异常，请从新扫码";
                    }else{
                        return this.ctx.body=" 服务器超时，请稍后重试！";
                    }
                }else{
                    return await this.ctx.render('book/book-auth-spc', res_data.data);
                }
            }catch(error){
                logger.error("bookauthRouter find error:",error)
                ctx.cookies.set('token'," ");
                return this.ctx.body="登录异常，请从新扫码！";
            }
        }
        //如果不存在code，则跳转微信登陆
        if (!ctx.query.code) {
            let has_ex = ctx.query.has_ex?ctx.query.has_ex:0;
            return ctx.redirect(await ctx.service.wxService.getWxLoginUrl(app.config.APPID,url, app.config.USER_INFO,has_ex));
        } else {
            let ip = ctx.headers["x-real-ip"];
            try{
                let login_data =  await ctx.service.wxService.login(ctx.query.code, ip)
                if (login_data.res_code != 1) {
                    ctx.body='登录异常，请从新扫码！';
                    return;
                }
                ctx.cookies.set('token', login_data.msg, { expires: new Date(Date.now() + 1000 * 3600 * 24) });
                let res_data = await ctx.service.bookauthService.GetBookDetail(ctx, login_data.msg);
                if(res_data.rescode=="error"){
                    ctx.cookies.set('token'," ");
                    if(res_data.err=="first"){
                        return this.ctx.body="登录异常，请从新扫码";
                    }else{
                        return this.ctx.body=" 服务器超时，请稍后重试！";
                    }
                }else{
                    return await this.ctx.render('book/book-auth-spc', res_data.data);
                }
            }catch(error){
                logger.error("bookauthRouter find error:",error)
                ctx.body="请从新扫码，使用微信登陆！";
            }
        }
    }

}
module.exports = bookdetailController;

